<?php
/**
 * Created by PhpStorm.
 * User: cy
 * Date: 18-3-3
 * Time: 下午2:32
 * 秒杀程序,主要用于接受秒杀请求，存入redis
 */
class Seckill
{
    private $goodsId;//秒杀商品的id
    private $uid;//秒杀商品的用户id
    private $redisKey;//存入redis list key
    private $redisCount;//存入redis list key


    private $redis;
    public function __construct($uid,$goodsId)
    {
        $this->uid=$uid;
        $this->goodsId=$goodsId;
        $this->redisKey='seckill_list_'.$goodsId;
        $this->redisCount='seckill_count_'.$goodsId;

        $this->redis=$this->getRedis();
    }
    //获取redis
    public function getRedis()
    {
        $redis=new Redis();
        $redis->connect('127.0.0.1', 6379);
        return $redis;
    }

    //检查秒杀数量是否已经超额
    private function checkNum()
    {
        $res=$this->redis->lPop($this->redisCount);
        return $res?true:false;

    }
    //将秒杀请求信息放入redis队列
    public function saveToRedis()
    {
        if(!$this->checkNum()){
            return "秒杀已完成\n";
        }else{
            //将数据存入redis
            $strData=$this->uid.'|'.$this->goodsId.'|'.microtime();
            $res =$this->redis->lPush($this->redisKey,$strData);
            if($res){
                return "sucesss\n";
            }else{
                return "fail\n";
            }
        }
    }

}

$uid=rand(10000,99999);
$goodsId=10;
$seckill= new Seckill($uid,$goodsId);
echo $seckill->saveToRedis();